package com.mucd.blog.util;

import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTHeader;
import cn.hutool.jwt.JWTUtil;
import com.mucd.blog.entity.MyUserEntity;

import java.util.HashMap;
import java.util.Map;

/**
 * @author mucd
 * @date 2022/6/1 2022/6/1
 */
public class TokenUtil {
    /**
     * token 过期时间
     */
    private final Long EXPIRE_TIME =  1000 * 60 * 60 * 24L;

    /**
     * 创建token
     *
     * @param user user
     * @return token
     */
    public String createToken(MyUserEntity user) {
        Map<String, Object> map = new HashMap<String, Object>() {
            private static final long serialVersionUID = 1L;
            {
                put("uid", user.getUsernameId());
                put("create_time", System.currentTimeMillis());
                put("expire_time", System.currentTimeMillis() + EXPIRE_TIME);
            }
        };
        //生成token
        return JWTUtil.createToken(map, user.getUserPassword().getBytes());
    }


    /**
     * true 验证成功
     *
     * @param token token
     * @param user  user
     * @return true and false
     */
    public Boolean verifyToken(String token, MyUserEntity user) {
        return JWTUtil.verify(token, user.getUserPassword().getBytes());
    }

    /**
     * 解析token
     * @param token
     * @param user
     * @return
     */
    public Map<String, Object> parseToken(String token, MyUserEntity user) {
        final JWT jwt = JWTUtil.parseToken(token);

        jwt.getHeader(JWTHeader.TYPE);
//        JSONObject payloads = jwt.getPayloads();

        Map<String, Object> map = new HashMap<>();
        map.put("uid", jwt.getPayload("uid"));
        map.put("expire_time", jwt.getPayload("expire_time"));
        map.put("create_time", jwt.getPayload("create_time"));

        return map;
    }

    /*public static void main(String[] args) {
        TokenUtil tokenUtil = new TokenUtil();
        MyUserEntity myUserEntity = new MyUserEntity();
        myUserEntity.setUsernameId(1L);
        myUserEntity.setUserName("zhangsan");
        myUserEntity.setUserPassword("123123");

        //create
        String token = tokenUtil.createToken(myUserEntity);
        System.out.println(tokenUtil.verifyToken(token, myUserEntity));

        System.out.println(tokenUtil.parseToken(token, myUserEntity));
    }*/
}
